#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

// Quita los caracteres del tipo [1],  [2], etc que aparecen al copiar los articulos de wikipedia.


void removeCharacters(char * file)
{
	if ( strlen(file) < 5) return;
	if ( file[ strlen(file) - 1 ] == '~') return;
	if ( file[ strlen(file) - 1 ] != 't') return;
	if ( file[ strlen(file) - 2 ] != 'x') return;
	if ( file[ strlen(file) - 3 ] != 't') return;
	if ( file[ strlen(file) - 4 ] != '.') return;
	if ( file[ strlen(file) - 6 ] == '_' && file[ strlen(file) - 5 ] == 'p') return;
	
	char fileWrite[strlen(file) + 2];
	strcpy(fileWrite, file);
	for (int i = 0; i < 5; i++)
	{
		fileWrite[strlen(file) + 2 - i] =  fileWrite[strlen(file) - i];
	}
	fileWrite[strlen(file) - 4] = '_';
	fileWrite[strlen(file) - 3] = 'p';
	
	FILE * fdWrite;
	fdWrite = fopen(fileWrite, "w");
	FILE * fdRead;
	fdRead = fopen(file, "r");

	bool waitingForBrackets = false;;
	char ch = fgetc ( fdRead ); 
	fputc( ch, fdWrite);

	while (ch != EOF)
	{
		ch = fgetc ( fdRead );
		if (ch == '[')
		{
			waitingForBrackets = true;
			continue;
		}
		
		if (waitingForBrackets == true)
		{
			if (ch == ']') waitingForBrackets = false;
			continue;
		}
		
		if (ch != EOF) fputc( ch, fdWrite);
	}
	
	fclose(fdWrite);
	fclose(fdRead);
}

int main(int argc,char *argv[])
{
	DIR *dir;
    struct dirent *dent;
    dir = opendir("./");
    
    if(dir != NULL)
    {
        while( (dent=readdir(dir)) != NULL )
			removeCharacters( dent->d_name );
    }
	
	return 1;
}
